<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once (APPPATH . 'libraries/groupobject.php');

/**
 * Group Model
 */
class Group_Model extends CI_Model
{

	function __construct()
	{
		parent::__construct();
	}

	public function getAllGroups()
	{
		$groups = array();

		$data = $this->db->get(GROUPS_TABLE);

		foreach ($data->result() as $row)
		{
			$group = new GroupObject($row->id, $row->name, $row->admin);
			$groups[] = $group;
		}

		return $groups;
	}

	public function getGroupById($id)
	{
		$group = new GroupObject();

		$this->db->where('id', $id);
		$data = $this->db->get(GROUPS_TABLE);

		if ($data->num_rows() > 0)
		{
			$row = $data->row();
			$group->setId($row->id);
			$group->setName($row->name);
			$group->setAdmin($row->admin);
		}

		return $group;
	}
	
	public function insertGroup($group)
	{
		$query = "INSERT INTO ".GROUPS_TABLE." VALUES (NULL, ?, ?)";
		
		$this->db->trans_start();
		$this->db->query($query, array($group->getName(), $group->isAdmin()));
		$this->db->trans_complete();
		
		if ($this->trans_status() === FALSE)
			return INSERT_ERROR;
		
		return ERROR_NONE;
	}

	public function updateGroup($id, $group)
	{
		$query = 'UPDATE ' . GROUPS_TABLE . ' SET name=?, admin=? WHERE id=?';

		$this->db->trans_start();
		$this->db->query($query, array($group->getName(), $group->isAdmin(), $id));
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE)
		{
			return UPDATE_ERROR;
		}

		return ERROR_NONE;
	}

	public function deleteGroup($id)
	{
		$this->db->trans_start();
		$this->db->where('id', $id);
		$this->db->delete(GROUPS_TABLE);
		$this->db->trans_complete();

		if ($this->db->trans_status() === FALSE)
		{
			return DELETE_ERROR;
		}

		return ERROR_NONE;
	}

	public function isGroupExisted_id($id)
	{
		$this->db->where('id', $id);
		$data = $this->db->get(GROUPS_TABLE);

		return ($data->num_rows() > 0);
	}

	public function isGroupExisted_name($name)
	{
		$query = "SELECT id FROM " . GROUPS_TABLE . " WHERE name LIKE N'%" . $this->db->escape_like_str($name) . "%'";
		$data = $this->db->query($query);

		return ($data->num_rows() > 0);
	}

}
?>